package de.tg.handball.xml;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

public class RSSReader {

	public final String tag = "RSSReader";
	private RSSFeed feed = null;

	public RSSFeed getFeed(String urlToRssFeed) {
		HttpURLConnection conn = null;
		BufferedReader read = null;
		try {
			// setup the url
			conn = (HttpURLConnection) new URL(urlToRssFeed).openConnection();
			conn.setConnectTimeout(5000);
			read = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "iso-8859-1"));
			
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();

			XMLReader xmlreader = parser.getXMLReader();
			RSSHandler theRssHandler = new RSSHandler();
			xmlreader.setContentHandler(theRssHandler);
			InputSource is = new InputSource(read);
			
			xmlreader.parse(is);
			feed = theRssHandler.getFeed();
			return feed;
		} catch (Exception ee) {
			ee.printStackTrace();
			return null;
		}finally {
			if (read != null)
				try {
					read.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (conn != null)
				conn.disconnect();
		}
		
	}
}